package com.zzyweb.rentalcarsys.controller;

import cn.hutool.core.util.IdUtil;
import com.zzyweb.rentalcarsys.entity.Car;
import com.zzyweb.rentalcarsys.service.CarService;
import com.zzyweb.rentalcarsys.utils.PageResult;
import com.zzyweb.rentalcarsys.utils.ResponseObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author zhiyi
 * @date 10/10/25
 **/
@RestController
@RequestMapping("/car")
@CrossOrigin
public class CarController {
    @Autowired
    CarService carService;
    @GetMapping("/all")
    ResponseObject getAllCars(@RequestParam Long currentPage, @RequestParam Long pageSize) {
        PageResult<Car> allCar = carService.getAllCar(currentPage, pageSize, null);
        return ResponseObject.ok(allCar);
    }

    @PostMapping("/conditions")
    ResponseObject getByConditions(@RequestParam Long currentPage, @RequestParam Long pageSize, @RequestBody Car car) {
        PageResult<Car> cars = carService.getAllCar(currentPage,pageSize,car);
        return ResponseObject.ok(cars);
    }
    @PutMapping("/modify")
    ResponseObject modifyCar(@RequestBody Car car) {
        carService.modifyCar(car);
        return ResponseObject.ok();
    }
    @PostMapping("/add")
    ResponseObject addCar(@RequestBody Car car) {
        carService.addCar(car);
        return ResponseObject.ok();
    }
    @PostMapping("/uploadPicture")
    ResponseObject fileUpload(@RequestBody MultipartFile file) throws IOException {
        //设定存储路径
        String path = "/Users/zhiyi/woniu/nginxdata/car/";
        //设定访问路径
        String baseUrl = "http://localhost:8080/car";
        //设置文件前缀
        String prefix = IdUtil.getSnowflakeNextIdStr();
        //获得原始文件名
        String originalName = file.getOriginalFilename();
        if (!StringUtils.hasText(originalName)) throw new RuntimeException("文件上传失败");
        String suffix = originalName.substring(originalName.lastIndexOf("."));
        String fileName = prefix + suffix;
        //文件存储到我们设定的路径中
        file.transferTo(new File(path,fileName));
        //返回访问地址
        String fullUrl = baseUrl + prefix+suffix;
        System.out.println("图片上传成功");
        return ResponseObject.ok(fullUrl);
    }
}
